<template>
  <div class="container">
    <navBar :navBar="navBar"></navBar>
    <van-tabs
      color="#2979FF"
      title-active-color="#2979FF"
      v-model="activeIndex"
    >
      <van-tab v-for="(item, index) in tabList" :key="index" :title="item">
        <div class="content" v-show="index == 0">
          <div class="listBox01 listBox">
            <div class="ttlBox">
              <p>{{ $t("价格") }}({{ $t("USDT") }})</p>
              <p>{{ $t("数量") }}({{ $t("BTC") }})</p>
              <p>{{ $t("价格") }}({{ $t("USDT") }})</p>
              <p>{{ $t("数量") }}({{ $t("BTC") }})</p>
            </div>
            <div class="innerBox">
              <div class="itemBox" v-for="(item, index) in data01" :key="index">
                <template>
                  <p v-if="item && item.price">{{ item.price }}</p>
                  <p v-if="item && item.amount">{{ item.amount.toFixed(6) }}</p>
                </template>
              </div>
              <div
                class="itemBox"
                v-for="(item, index) in data02"
                :key="index + 10"
              >
                <template>
                  <p v-if="item && item.price">{{ item.price }}</p>
                  <p v-if="item && item.amount">{{ item.amount.toFixed(6) }}</p>
                </template>
              </div>
            </div>
          </div>
        </div>
        <div class="content" v-show="index == 1">
          <div class="listBox02 listBox">
            <div class="ttlBox">
              <p>{{ $t("产品") }}</p>
              <p>{{ $t("成交价") }}</p>
              <p>{{ $t("方向") }}</p>
              <p>{{ $t("时间") }}</p>
            </div>
            <div
              class="itemBox"
              v-for="(item, index) in symbolsArray"
              :key="index"
            >
              <template>
                <p>{{ item.title }}</p>
                <p v-if="ch[`market.${item.symbol}.trade.detail`]">
                  {{
                    ch[`market.${item.symbol}.trade.detail`].tick.data[0].price
                  }}
                </p>
                <p
                 v-if="ch[`market.${item.symbol}.trade.detail`]"
                  :class="
                    ch[`market.${item.symbol}.trade.detail`].tick.data[0]
                      .direction == 'buy'
                      ? 'green'
                      : 'red'
                  "
                >
                  {{
                    ch[`market.${item.symbol}.trade.detail`].tick.data[0]
                      .direction == "buy"
                      ? "买入"
                      : "卖出"
                  }}
                </p>
                <p v-if="ch[`market.${item.symbol}.trade.detail`]">
                  {{
                    ch[`market.${item.symbol}.trade.detail`].tick.data[0].date
                  }}
                </p>
              </template>
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>
    <loading v-if="showLoading" :show="showLoading"></loading>
  </div>
</template>

<script>
import navBar from "@/components/navBar.vue";
import { EventBus } from "@/utils/event-bus";
export default {
  name: "tradeRecord",
  components: { navBar },
  data() {
    return {
      navBar: {
        back: true,
        title: this.$t("实时数据"),
        close: false,
        btn: "",
        isBlue: true,
      },
      activeIndex: 0,
      // 币种列表
      symbolsArray: [
        { symbol: "btcusdt", title: "BTC/USDT" },
        { symbol: "ethusdt", title: "ETH/USDT" },
        { symbol: "eosusdt", title: "EOS/USDT" },
        { symbol: "crousdt", title: "CRO/USDT" },
        { symbol: "trxusdt", title: "TRX/USDT" },
      ],
      ch: {}, //  实时成交
      tabList: [this.$t("实时数据"), this.$t("实时成交")],
      data01: [],
      data02: [],
      datas: [], //  实时数据
      showLoading: true,
    };
  },
  created() {
    if (this.$route.query.type == "1") {
      this.activeIndex = 0;
    } else if (this.$route.query.type == "2") {
      this.activeIndex = 1;
    }
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      this.$nextTick(async () => {
        this.symbolsArray = await this.initMarketInfo();
        let Interval = setInterval(() => {
          if (this.$store.state.websocket.is_open_socket) {
            this.loadTopMarket();
            this.send();
            this.clinchDealSend();
            // 已连接移除定时器
            clearInterval(Interval);
          }
        }, 500);
        this.$forceUpdate();
      });
    },
    //  最新市场概要快照
    loadTopMarket() {
      this.symbolsArray.forEach((item) => {
        let ch = `market.${item.symbol}.detail`;
        let data = {
          sub: ch,
          id: Date.now() + "",
        };
        // 发送消息
        this.$store.dispatch("WEBSOCKET_SEND", JSON.stringify(data));
        let ch2 = `market.${item.symbol}.trade.detail`;
        let data2 = {
          sub: ch2,
          id: "id1",
        };
        this.$store.dispatch("WEBSOCKET_SEND", JSON.stringify(data2));
      });
    },
    // 获取交易对数据
    async initMarketInfo() {
      const result = await new Promise((resolve) => {
        $postAxios(api.getMarket, {}, (res) => {
          if (res.code == 0) {
            let arr = res.data.map((item) => {
              let obj = {
                symbol: String(item.EN_name).toLowerCase() + "usdt",
                title: item.EN_name + "/USD",
                note: item.EN_name,
                bi_id: item.bi_id,
                is_zixuan: item.is_zixuan,
              };
              return obj;
            });
            resolve(arr);
          } else {
            this.$toast(this.$t(res.msg));
          }
        });
      });
      return result;
    },
    //  实时数据订阅
    send() {
      this.showLoading = true;
      let ch = `market.${
        JSON.parse(localStorage.getItem("symbol")).symbol
      }.trade.detail`;
      EventBus.$on(ch, (res) => {
        let newRes = res.data.tick.data.concat(this.datas);
        this.datas = newRes;
        this.datas.length = 20;
        this.data01 = this.datas.slice(0, 9);
        this.data02 = this.datas.slice(10, 19);
      });
      this.showLoading = false;
    },
    //  实时成交订阅
    clinchDealSend() {
      this.showLoading = true;
      this.symbolsArray.forEach((item) => {
        let ch = `market.${item.symbol}.trade.detail`;
        EventBus.$on(ch, (res) => {
          // 时间转换
          let date = new Date(res.data.tick.data[0].ts);
          res.data.tick.data[0].date = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
          this.$set(this.ch, res.data.ch, res.data);
        });
      });
      this.showLoading = false;
      // console.log(this.ch, "ch");
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding-top: 40px;
  width: 100%;
  min-height: 100vh;
  height: 100%;
  box-sizing: border-box;
  background-color: #f7f6fb;
  .content {
    padding: 10px;
    .listBox {
      padding: 20px;
      border-radius: 8px;
      background-color: #fff;
      .ttlBox {
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        p {
          min-width: 70px;
          color: #000;
          font-size: 12px;
          text-align: right;
        }
      }
      .innerBox {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
      }
      .itemBox {
        margin-bottom: 10px;
        width: 48%;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        p {
          min-width: 70px;
          color: #000;
          font-size: 12px;
          text-align: right;
          &:nth-child(1) {
            color: #1cad90;
          }
          &:nth-child(3) {
            color: #db6964;
          }
        }
      }
    }
    .listBox02 {
      padding: 10px 20px;
      .ttlBox {
        margin-bottom: 10px;
        padding-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: solid 1px #e6eaed;
        p {
          min-width: 70px;
          color: #000;
          font-size: 12px;
          text-align: left;
          &:nth-child(1) {
            padding-left: 10px;
            flex: 1;
          }
          &:nth-child(2) {
            min-width: 80px;
            text-align: right;
          }
          &:nth-child(3) {
            width: 20%;
            text-align: center;
          }
          &:nth-child(4) {
            width: 20%;
            text-align: center;
          }
        }
      }
      .itemBox {
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        p {
          min-width: 70px;
          color: #000;
          font-size: 12px;
          text-align: left;
          &:nth-child(1) {
            min-width: 95px;
            flex: 1;
            color: #000;
          }
          &:nth-child(2) {
            min-width: 80px;
            text-align: right;
          }
          &:nth-child(3) {
            width: 20%;
            color: #1cad90;
            text-align: center;
          }
          &:nth-child(4) {
            width: 20%;
            text-align: center;
          }
          &.red {
            color: #db6964;
          }
        }
      }
    }
  }
}
</style>